<template>
  <div>
    <div class="search-title">查询条件</div>
    <div class="search-box">
      <a-form-model :model="searchForm" layout="inline" ref="searchForm" class="searchForm">
        <a-form-model-item label="角色名称"  prop="roleName">
          <a-input v-model="searchForm.roleName" placeholder="请输入角色名称"/>
        </a-form-model-item>
        <a-form-model-item class="searchButton">
          <a-button type="primary" v-if="QX.read" @click="getSearch">查询</a-button>
          <a-button type="default" v-if="QX.read" @click="restSearch('searchForm')">重置</a-button>
        </a-form-model-item>
      </a-form-model>
    </div>
    <div class="table-operation">
      <a-button type="primary" @click="addRole" icon="plus" v-if="QX.add">新增</a-button>
    </div>
    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="false"
      :loading="loading"
      rowKey="roleId"
      :scroll="{y: this.$getViewportSize().height-300 }">
      <span slot="action" slot-scope="text,record">
        <a @click="editAuth(record)" v-if="QX.edit"><a-icon class="iconBtn" type="edit" />编辑</a>
        <a-divider v-if="QX.edit && QX.delete" type="vertical"/>
        <a-popconfirm
          title="确认是否删除？"
          ok-text="是"
          cancel-text="否"
          @confirm="removeRole(record)"
        >
          <a v-if="QX.delete"><a-icon class="iconBtn" type="delete" />删除</a>
        </a-popconfirm>
      </span>
    </a-table>
    <a-pagination
      show-size-changer
      :total="totalPage"
      :current="pageIndex"
      :pageSize="pageSize"
      @showSizeChange="onShowSizeChange"
      @change="onChangePage"
      style="float: right;margin-top: 15px"
    />
    <a-drawer
      :closable="true"
      :title="title"
      width="auto"
      :visible="visible"
      @close="visible=!visible">
      <a-spin class="submitLoading" :spinning="submitLoading">
      <a-form-model :model="form" :label-col="labelCol" :wrapper-col="wrapperCol" :rules="rules" ref="form" class="lay-drawer-form">
        <a-form-model-item label="角色代号" prop="roleCode" >
          <a-input v-model="form.roleCode"
                   :maxLength="20"
                   oninput="if (value.charCodeAt(value.length-1)>65280 && value.charCodeAt(value.length-1)<65375)value=value.substr(0,value.length-1)"
                   placeholder="请输入角色代号" :disabled="disabled" style="width: 380px"/>
        </a-form-model-item>
        <a-form-model-item label="角色名称"  prop="roleName">
          <a-input v-model="form.roleName"
                   :maxLength="25"
                   placeholder="请输入角色名称" style="width: 380px"/>
        </a-form-model-item>
        <a-form-model-item label="选择权限">
          <vue-scroll :ops="ops" style="height:calc(100vh - 260px);height:-moz-calc(100vh - 260px);height: -webkit-calc(100vh - 260px);">
            <a-tree
              v-model="checkedKeys"
              checkable
              :tree-data="treeData"
              @check="check"
            />
          </vue-scroll>
        </a-form-model-item>
      </a-form-model>
      <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '8px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1,
        }">
        <a-button
          type="default"
          @click="visible=!visible"
        >
          取消
        </a-button>
        <a-button
          type="primary"
          @click="submitForm"
        >
          确认
        </a-button>
      </div>
      </a-spin>
    </a-drawer>
  </div>
</template>

<script>
import {req} from '../../../api/axiosFun'
import preventBack from 'vue-prevent-browser-back';
export default {
  name: "Role",
  mixins: [preventBack],//注入
  data() {
    return {
      QX: {},
      disabled: false,
      checkedKeys: [],
      selectAuth: [],
      treeData: [],
      title: '',
      labelCol: {span: 4},
      wrapperCol: {span: 20},
      tableHeight: 0,
      expanded: false,//筛选条件是否展开
      form: {
        roleId: 0,
        roleCode: '',
        roleName: '',
      },
      rules: {
        roleCode: [
          {required: true, message: '请输入角色代号', trigger: 'blur'},
        ],
        roleName: [
          {required: true, message: '请输入角色名称', trigger: 'blur'},
        ],
      },
      searchForm: {
        roleName: '',
      },
      visible: false,
      dataList: [],
      columns,
      loading: false,
      submitLoading: false,
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      ops: {
        vuescroll: {},
        scrollPanel: {},
        rail: {
          keepShow: true
        },
        bar: {
          hoverStyle: true,
          onlyShowBarOnScroll: false, //是否只有滚动的时候才显示滚动条
          background: "#F5F5F5",//滚动条颜色
          opacity: 1,//滚动条透明度
          "overflow-x": "hidden"
        }
      },
    }
  },
  watch: {
    visible(newVal, oldVal) {
      if (!newVal) {
        this.restForm('form');
        this.form.roleId = 0
        this.checkedKeys = [];
        this.selectAuth = [];
        this.treeData = [];
      }
    }
  },
  mounted() {
    this.getRoleList();
    this.actionTitle = '操作';
  },
  methods: {
    /* 功能权限树点击复选框触发事件 */
    check(checkedKeys, e) {
      let selectAuth = [];
      if (!checkedKeys || !checkedKeys.length) {
        this.selectAuth = [];
      }
      checkedKeys.forEach((key, index) => {
        //key包含-
        if (key.includes('-')) {
          selectAuth.push(key);
        }
      });
      this.selectAuth = selectAuth;
    },
    /* 新增角色 */
    addRole() {
      this.visible = true;
      this.disabled = false;
      this.title = '新增角色';
      //获取功能权限树
      req("get", '/role/getTree', {}).then(res => {
        this.treeData = res.data;
      });
    },
    //查询
    getSearch() {
      this.pageIndex = 1
      this.getRoleList()
    },
    /* 重置查询 */
    restSearch(form) {
      this.restForm(form);
      this.pageIndex = 1
      this.getRoleList();
    },
    /* 删除角色 */
    removeRole(record) {
      this.loading = true
      req("post", '/role/removeRole', {
        roleId: record.roleId
      }).then(res => {
        this.loading = false
        if (res.result === 'success') {
          this.$message.success(res.message);
          this.getRoleList();
        }
      });
    },
    /* 编辑角色信息 */
    editAuth(record) {
      this.loading = true
      req("post", '/role/getRoleById', {
        roleId: record.roleId
      }).then(res => {
        this.loading = false
        if (res.result === 'success') {
          this.visible = true;
          this.disabled = true;
          this.title = '修改角色';
          let role = res.data;
          this.$nextTick(() => {
            this.form.roleId = role.roleId;
            this.form.roleCode = role.roleCode;
            this.form.roleName = role.roleName;
            this.treeData = role.treeData;
            this.checkedKeys = role.auths;
            this.checkedKeys.forEach((key, index) => {
              //key包含-
              if (key.includes('-')) {
                this.selectAuth.push(key);
              }
            });
          })
        }
      });
    },
    /* 保存or修改角色信息 */
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const url = this.form.roleId ? 'updateRole' : 'addRole';
          let selectAuth = this.selectAuth;
          this.form.selectAuth = JSON.stringify(selectAuth);
          this.submitLoading = true
          req("post", `/role/${url}`, this.form).then(res => {
            if (res.result === 'success') {
              this.visible = false;
              this.getRoleList();
              this.$message.success(res.message);
            }
            this.submitLoading = false
          });
        }
      });
    },
    /* 重置表单 */
    restForm(form) {
      this.$refs[form].resetFields();
    },
    /* 改变页数事件 */
    onChangePage(page, pageSize) {
      this.pageIndex = page;
      this.getRoleList();
    },
    /* 改变每页显示条数 */
    onShowSizeChange(current, pageSize) {
      this.pageIndex = 1;
      this.pageSize = pageSize;
      this.getRoleList();
    },
    /* 角色信息列表 */
    getRoleList() {
      this.loading = true;
      this.searchForm.page = this.pageIndex;
      this.searchForm.rows = this.pageSize;
      req("post", `/role/getRoleListPage`, this.searchForm)
        .then(res => {
          if (res.result === 'success') {
            this.dataList = res.data;
            this.QX = res.QX;
            //无权限隐藏操作列
            if (!this.QX.edit && !this.QX.delete) {
              this.hideAction();
            }else if(columns[columns.length - 1].title!='操作'){
              columns.push(actionShow);
            }
            this.totalPage = res.page.totalResult;
          }
          this.loading = false;
        }).catch(error=> {
        this.loading = false;
      });
    },
    /*无所有行操作权限时,隐藏操作栏*/
    hideAction() {
      if (columns[columns.length - 1].title == '操作') {
        columns.splice(columns.length - 1, 1)
      }
    },
    /*校验代号类型*/
    validCode(value) {
      if(value.length>20){
        value=value.slice(0,20);
      }
      for (let i = value.length-1; i >= 0; i--)
      {
        let unicode=value.charCodeAt(i);
        if (unicode>65280 && unicode<65375)
        {
          value=value.substr(0,i);
        }
      }
      this.value = value;
    }
  }
}
const actionShow =  {
  title: '操作',
  width: '200px',
  hide: true,
  dataIndex: 'action',
  key: 'action',
  align: 'center',
  scopedSlots: {customRender: 'action'},
}

const columns = [
  {
    title: '序号',
    width:'50px',
    align: 'center',
    customRender: (text, row, index) => {
      return index+1;
    },
  },
  {
    title: '角色名称',
    align: 'center',
    dataIndex: 'roleName',
    key: 'roleName',
    width:'120px',
  },
  {
    title: '创建者',
    align: 'center',
    dataIndex: 'createUser',
    key: 'createUser',
    width:'110px',
  },
  {
    title: '创建时间',
    dataIndex: 'createDatetime',
    key: 'createDatetime',
    align:'center',
    width:'180px',
  },
  {
    title: '更新者',
    align: 'center',
    dataIndex: 'updateUser',
    key: 'updateUser',
    width:'110px',
  },
  {
    title: '更新时间',
    dataIndex: 'updateDatetime',
    key: 'updateDatetime',
    align:'center',
    width:'180px',
  },
  {
    title: '操作',
    width: '150px',
    hide: true,
    dataIndex: 'action',
    key: 'action',
    align: 'center',
    scopedSlots: {customRender: 'action'},
  },
];
</script>

<style scoped>
@import "../../../assets/css/maincss.css";

</style>
